package com.mytrip.util;

import java.util.Random;

import com.mytrip.webapp.session.SessionBagImpl;

/**
 * @project backend
 * 
 * @author <a href="mailto:yuanchongyu1@163.com">yuanchongyu</a>
 * 
 * @createDate Jul 1, 2010 3:18:56 PM
 * 
 */
public final class SessionMemcacheUtil{
	public static String COOKIE_SESSION_KEY = "SessionBag";

	private static String PREFIX_TO_MC = "s_";

	// 过期时间 30分钟
	public static final int EXPIR_MINS = 30;

	// key 的长度(不包含前缀s_)
	private static final int MEMCACHE_KEY_LEN = 30;

	// 随机字符串
	private static char[] NUM_AND_LETTER = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
			.toCharArray();

	private static int NUM_AND_LETTER_LEN = 62;

	public static String getRandomMemcacheKey(){
		return getRandomStr(MEMCACHE_KEY_LEN);
	}

	public static void put(String memcacheKey, SessionBagImpl sessionBag){
		sessionBag.freshUpdate();
		MemcachedProxy.getInstance().put(PREFIX_TO_MC + memcacheKey, sessionBag, EXPIR_MINS);
	}

	public static SessionBagImpl get(String memcacheKey){
		return (SessionBagImpl) MemcachedProxy.getInstance().get(PREFIX_TO_MC + memcacheKey);
	}

	private static String getRandomStr(int len){
		if (len <= 0) {
			return "";
		}
		Random r = new Random();
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < len; i++) {
			sb.append(NUM_AND_LETTER[r.nextInt(NUM_AND_LETTER_LEN - 1)]);
		}
		return sb.toString();
	}
}
